import { TypeormBuilder } from '../../common/query.builder';
import { LoggerUtility } from '../../logger/logger.utility';
import { MySQLUtils } from '../../utility/mysql.utility';
import { Utility } from '../../utility/utility';
import { DictionaryItem } from '../entity/dictionaryitem';

// tslint:disable:triple-equals
// tslint:disable:max-line-length
export class DictionaryItemHandler {
    public async insert(body: any): Promise<{ flag: boolean, output: any }> {
        return MySQLUtils.getConnection().then(async (connection) => {
            const paraResult = this.insertParse(body);
            if (paraResult.flag) {
                const result = await MySQLUtils.Save(connection, paraResult.output);
                return { flag: result.flag, output: result.newEntity };
            } else {
                return { flag: paraResult.flag, output: paraResult.output };
            }
        });
    }

    public async update(body: any): Promise<{ flag: boolean, output: any }> {
        return MySQLUtils.getConnection().then(async (connection) => {
            const paraResult = this.updateCheck(body);
            if (paraResult.flag) {
                const curItem = await connection.createQueryBuilder(DictionaryItem, 'item')
                    .where('item.item_id = :itemId and item.enabled = 1', { itemId: body.itemId })
                    .getOne();
                if (curItem != null) {
                    curItem.dictionaryId = body.dictionaryId ? +body.dictionaryId : 1;
                    curItem.code = body.code;
                    curItem.value = body.value;
                    curItem.comment = body.comment;
                    const result = await MySQLUtils.Save(connection, curItem);
                    return { flag: result.flag, output: result.newEntity };
                } else {
                    LoggerUtility.error('DictionaryItemHandler update no id:'
                        + body.itemId, undefined);
                    return {
                        flag: false,
                        output: 'DictionaryItemHandler update no id:' + body.itemId,
                    };
                }
            } else {
                return { flag: paraResult.flag, output: paraResult.output };
            }
        });
    }

    public async delete(query: any): Promise<{ flag: boolean, output: any }> {
        return MySQLUtils.getConnection().then(async (connection) => {
            const paraResult = this.deleteCheck(query);
            if (paraResult.flag) {
                const item = await connection.createQueryBuilder(DictionaryItem, 'item')
                    .where('item.item_id = :itemId and item.enabled = 1', { itemId: query.itemId })
                    .getOne();
                if (item != null) {
                    item.enabled = 0;
                    const result = await MySQLUtils.Save(connection, item);
                    return { flag: result.flag, output: result.newEntity };
                } else {
                    LoggerUtility.error('DictionaryItemHandler delete cannot find id:'
                        + query.itemId, undefined);
                    return {
                        flag: false,
                        output: 'DictionaryItemHandler delete cannot find id: - ' + query.itemId,
                    };
                }
            } else {
                return { flag: paraResult.flag, output: paraResult.output };
            }
        });
    }

    public async query(query: any): Promise<{ flag: boolean, output: any }> {
        const queryItem = this.queryParaParse(query);
        if (queryItem.flag) {
            return MySQLUtils.getConnection().then(async (connection) => {
                const item = queryItem.output as DictionaryQueryItem;
                let qb = connection.createQueryBuilder(DictionaryItem, 'item');
                qb = TypeormBuilder.addNumberEquals([
                    { key: 'item_id', value: item.itemId },
                ], 'item', qb);
                qb = TypeormBuilder.addStringEquals([
                    { key: 'code', value: item.code },
                ], 'item', qb);
                qb.andWhere('item.enabled = 1');
                const items = await qb.getMany();
                return { flag: true, output: items };
            });
        } else {
            return { flag: false, output: queryItem.output };
        }
    }

    public insertParse(body: any): { flag: boolean, output: any } {
        if (!Utility.String.isBlank(body.code) && !Utility.String.isBlank(body.value)) {
            try {
                const item = new DictionaryItem();
                item.dictionaryId = body.dictionaryId ? +body.dictionaryId : 1;
                item.code = body.code;
                item.value = body.value;
                item.comment = body.comment;
                item.enabled = 1;
                return { flag: true, output: item };
            } catch (error) {
                LoggerUtility.error('DictionaryItemHandler insertParse - code' + body.code, error);
                return { flag: false, output: 'DictionaryItemHandler insertParse - error:' + error };
            }
        } else {
            LoggerUtility.warn('DictionaryItemHandler insertParse parameter unpass.');
            return {
                flag: false,
                output: 'DictionaryItemHandler insertParse - code,value cannot be empty',
            };
        }
    }

    public updateCheck(body): { flag: boolean, output: DictionaryItem | string } {
        if (!Utility.Number.isBlank(+body.itemId) && !Utility.String.isBlank(body.code)
            && !Utility.String.isBlank(body.value)) {
            return { flag: true, output: body };
        } else {
            LoggerUtility.warn('DictionaryItemHandler updateCheck parameter unpass.');
            return {
                flag: false,
                output: 'DictionaryItemHandler updateCheck - itemId,code,value cannot be empty',
            };
        }
    }

    public deleteCheck(query: any): { flag: boolean, output: any } {
        if (!Utility.Number.isBlank(+query.itemId)) {
            return { flag: true, output: query };
        } else {
            return { flag: false, output: 'DictionaryItemHandler deleteCheck - itemId cannot be empty' };
        }
    }

    public queryParaParse(query: any): { flag: boolean, output: DictionaryQueryItem | string } {
        const queryitem = new DictionaryQueryItem();
        try {
            queryitem.itemId = query.itemId ? +query.itemId : undefined;
            queryitem.code = query.code ? query.code : undefined;
            return { flag: true, output: queryitem };
        } catch (error) {
            LoggerUtility.error('DictionaryItemHandler queryParaParse', error);
            return { flag: false, output: 'DictionaryItemHandler queryParaParse - error:' + error };
        }
    }
}

// tslint:disable-next-line:max-classes-per-file
class DictionaryQueryItem {
    public itemId: number;
    public code: string;
}
